import utils from '../public/utils'
let Fly = require("../public/wx.umd.min.js")
let fly = new Fly()
let num = 0

fly.config.timeout = 10000

fly.interceptors.request.use((request) => {
  num++
  // uni.showLoading({
  //   title: '加载中',
  //   mask: true
  // })
  return request
})

fly.interceptors.response.use((response) => {
	if (response.data.reCode == 401) {
		  uni.reLaunch({
		    url: '/pages/login/login'
		  })
	}
	if(response.data.reCode >= 500){
		uni.showLoading({
			title: '服务器错误！',
			mask: true
		},3000);
	}
  num--
  if (num <= 0) {
    uni.hideLoading()
  } else {
    // uni.showLoading({
    //   title: '加载中',
    //   mask: true
    // })
  }
  return response.data
}, (err) => {
  num = 0
  uni.hideLoading()

  //token失效重新登录
  if (err.status == 401) {
	  uni.reLaunch({
	    url: '/pages/login/login'
	  })
  }
})

const get = (url, params, headers = {"Content-Type": "application/json"}) => {
  params = Object.assign({token: uni.getStorageSync('token')},params)
  return new Promise((resolve, reject) => {
    fly.request(url, params, {
      method: "get",
      headers: headers,
      baseURL: utils.apiUrl
    }).then(response => {
      resolve(response)
    }, err => {
		console.log(err);
      reject(err)
    }).catch((error) => {
      reject(error)
    })
  })
}



const post = (url, params, headers = {"Content-Type": "application/json"}) => {
  params = Object.assign({token: uni.getStorageSync('token')},params)
  return new Promise((resolve, reject) => {
    fly.request(url, params, {
      method: "post",
      headers: headers,
      baseURL: utils.apiUrl
    }).then(response => {
      resolve(response)
    }, err => {
		console.log(err)
		if(err.message == 'timeout [ 10000ms ]'){	
			uni.showToast({
			    title: '请求超时！请重试',
				icon:'none',
			    duration: 2000
			});
		}
		if(err.status == '404'){
			uni.showToast({
			    title: '网页或文件未找到，请联系工作人员',
				icon:'none',
			    duration: 2000
			});
		}
		if(err.message.indexOf('request:fail abort statusCode:-1') != -1){
			uni.showToast({
			    title: '网络断开，请连接网络',
				icon:'none',
			    duration: 2000
			});
		}
		// setTimeout(()=>{
		// 	uni.navigateBack()
		// },800)
		const pages = getCurrentPages()
		const page = pages[pages.length - 1]
		const backs = page.$vm.$options.onBackPress
		if(page.route.split('/')[page.route.split('/').length-1]!='home'&&
		page.route.split('/')[page.route.split('/').length-1]!='health'&&
		page.route.split('/')[page.route.split('/').length-1]!='Popup'&&
		page.route.split('/')[page.route.split('/').length-1]!='Shopping'&&
		page.route.split('/')[page.route.split('/').length-1]!='mine'&&
		page.route.split('/')[page.route.split('/').length-1]!='login'&&
		page.route.split('/')[page.route.split('/').length-1]!='pwdLogin'){
			setTimeout(()=>{
				uni.navigateBack()
			},800)
		}
      reject(err)
    }).catch((error) => {
      reject(error)
    })
  })
}



export {
  get,
  post
}
